package com.yonyou.iuap.jxzy.servlet.service;

import java.util.List;

import nc.vo.pub.lang.UFDateTime;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.iuap.iweb.exception.BusinessException;
import com.yonyou.iuap.jxzy.entity.MonitorSample;
import com.yonyou.iuap.jxzy.service.MonitorSampleService;
import com.yonyou.iuap.jxzy.servlet.BaedDeviceService;
import com.yonyou.iuap.jxzy.servlet.DeviceInfo;
import com.yonyou.iuap.jxzy.servlet.dao.DeviceMapper;
import com.yonyou.iuap.jxzy.utils.HttpRequestUtil;

/**
 * 刷卡控制摄影业务扩展
 * @author WXF
 *
 */
@Service
public class ControlVideoService implements BaedDeviceService{

	public static final String DEVURL = "http://164.70.12.29:8080/unattended_hardware/hardwareOperation/uploadpic";

	public static final String LEDURL = "http://164.70.12.29:8080/unattended_hardware/hardwareOperation/showLedJX";

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private DeviceMapper deviceMapper;
	
	private MonitorSampleService monitorSampleService;

    @Autowired
    public void setMonitorSampleService(MonitorSampleService monitorSampleService) {
        this.monitorSampleService = monitorSampleService;
    }


	@Override
	public void processor(DeviceInfo deviceinfo) throws BusinessException {
		//更具卡号获取对应磅单主键
		String cardid = (String) deviceinfo.getUserData();
		String cardno=this.deviceMapper.queryCardnoByCardid(cardid);//根据卡id获取卡号
		if(cardno!=null && deviceinfo.getDeviceCode()!=null){
			String pk_pound = this.deviceMapper.queryPoundByCardno(cardno);//磅单主键
			if(pk_pound==null){
				this.processorled(deviceinfo,null,0,null,0);
				throw new BusinessException("根据卡号没有获取到未完成磅单!,请检查");
			}
			//TODO 获取上次刷卡时间,同榜单两小时内刷卡时间不能小于一分钟
			String getsksj = this.deviceMapper.getsksj(pk_pound);
			if(StringUtils.isNotEmpty(getsksj)){
				UFDateTime sksj = new UFDateTime(getsksj);
				UFDateTime currtime = new UFDateTime();
				if(currtime.getMillisAfter(sksj)<60000){
					
					throw new BusinessException("当前磅单刷卡时间小于一分钟!,请稍后再刷");
				}
			}
			List<String> list = this.deviceMapper.queryVideoByDevid(deviceinfo.getDeviceCode());
			JSONObject json = new JSONObject();
			json.put("pk_bill", pk_pound);
			json.put("deviceCodeList", list);
			if(list == null || list.size() == 0){
				logger.error("没有需要控制的摄像设备");
				throw new BusinessException("没有需要控制的摄像设备");
			}
			String result = HttpRequestUtil.sendPost(DEVURL, json.toJSONString());
			logger.error("摄像头抓拍json："+json+"，抓拍返回结果："+result);
			//调用对应的视频设备拍照
//			if(Boolean.FALSE.equals(new Boolean(result))){
//				logger.error("控制摄像拍照失败");
//				throw new BusinessException("控制摄像拍照失败");
//			}else {//如果摄像头调用成功，将刷卡设备名称中的抽样区截取出来存到磅单的抽样区字段
			
			//TODO 获取更新时间表前的数据
//			List<MonitorSample> queryBypk = monitorSampleService.queryBypk(pk_pound);
//			int nnum=0;
//			if(queryBypk.size()>0){
//				nnum=1;
//			}
			String sjpk = this.deviceMapper.getsksj(pk_pound);
			int nnum=0;
			if(StringUtils.isNotEmpty(sjpk)){
				nnum=1;
			}
			
				String devicename= deviceinfo.getDeviceName();
				String samparea=null;
				int sampleresult=0;
				if(devicename != null && devicename.contains("#")){
					samparea=devicename.split("#")[0]+"#";//抽样区
					logger.error("更新磅单："+pk_pound+",更新抽样区:"+samparea);
					sampleresult=this.deviceMapper.updateAreaToPound(pk_pound,samparea);//更新抽样区到磅单表
					//TODO 更新抽样刷卡时间
					this.deviceMapper.updatesksj(pk_pound, deviceinfo.getDeviceCode(), new UFDateTime().toStdString(), cardno);
					logger.error("更新磅单成功："+pk_pound+",更新抽样区成功:"+samparea+",更新磅单结果："+sampleresult);
				}
				if(samparea!=null && sampleresult==1){
					this.processorled(deviceinfo,samparea,1,pk_pound,nnum);
				}
				deviceinfo.setUserData(null);
//			}
		}
	}

	/**
	 * 显示到led
	 * @param deviceinfo
	 * @param samparea 
	 * @throws BusinessException
	 */
	public void processorled(DeviceInfo deviceinfo, String samparea,int type,String pk_pound,int numm) throws BusinessException {
		if(type==1){
			//根据抽样区查询设备明细获取led设备
			List<DeviceInfo> deviceInfoList=this.deviceMapper.queryLEDDeviceVO(samparea);
			if (deviceInfoList.size()>0) {
				logger.error("显示led的设备个数："+deviceInfoList.size());
				for(DeviceInfo dInfo:deviceInfoList) {
					String location=dInfo.getExtendClass();
					if(location!=null){
						//抽样区LED 
						if ("抽样区".equals(location)){
							if(dInfo.getDeviceCode()!=null && dInfo.getDeviceCode().length()>0){
//								String message="抽样区led显示："+samparea+"==磅单主键："+pk_pound+"==设备编码："+dInfo.getDeviceCode()+"==显示内容：抽包审核中，请稍等";
//								this.sendToLED(dInfo.getDeviceCode(), "抽包审核中，请稍等",message);
								//TODO 修改成自动触发加抽，需要先获取监控抽样的数据
								List<MonitorSample> queryBypk = monitorSampleService.queryBypk(pk_pound);
								if(queryBypk.size()>0){
									MonitorSample sample = queryBypk.get(0);
//									String getsksj = this.deviceMapper.getsksj(pk_pound);
//									if(StringUtils.isEmpty(getsksj)){
									if(numm==0){
										monitorSampleService.notSampleToAdd(sample);
									}else if(numm==1){
										monitorSampleService.auditPass(sample); 
									}
								}
							}
						}else if("办公室".equals(location)){
							if(dInfo.getDeviceCode()!=null && dInfo.getDeviceCode().length()>0){
								String message="办公室led显示："+samparea+"==磅单主键："+pk_pound+"==设备编码："+dInfo.getDeviceCode()+"==显示内容：抽包审核中，请稍等";
								this.sendToLED(dInfo.getDeviceCode(), samparea+"  抽包审核中，请稍等",message);
							}
						}
					}
				}
			}
		}else if(type==0){
			String ledcode=this.deviceMapper.getDivicecode(deviceinfo.getDeviceCode());//根据刷卡器编码获取led
			if(ledcode!=null){
				String message="异常信息led显示："+samparea+"==磅单主键："+pk_pound+"==设备编码："+ledcode+"==车辆未过磅";
				this.sendToLED(ledcode, "车辆未过磅",message);
			}
		}
	}

	public String sendToLED(String deviceCode,String LedText,String message){
		JSONObject json=new JSONObject();
		json.put("deviceCode", deviceCode);
		json.put("ledText", LedText);
		String result=HttpRequestUtil.sendPost2(LEDURL, json.toString());
		if("".equals(result)|| Boolean.FALSE.equals(new Boolean(result))){
			logger.error("led返回结果："+result+"==显示文字："+LedText+"==设备编码："+deviceCode+"，LED显示异常");
		}else{
			logger.error("led返回结果："+result+"==显示文字："+LedText+"=="+message);
		}
		return result;

	}

}
